package hamaster.jpbc.mgr;

import hamaster.jpbc.pbc.PBC;
import hamaster.jpbc.pbc.io.ID;
import hamaster.jpbc.pbc.io.IDIO;
import hamaster.jpbc.pbc.io.SimpleIDFileIOImpl;
import hamaster.jpbc.pbs.PBS;
import hamaster.jpbc.pbs.Signature;
import hamaster.jpbc.util.Hash;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

/**
 * 数据签名线程
 * @author <a href="mailto:wangyeee@gmail.com">Wang Ye</a>
 */
class SignatureThread implements Runnable {

	private File plain;
	private File folder;
	private File idFile;
	private Properties content;
	private String cipherName;
	private boolean sign;
	private SymmetricEncryptManager manager;

	public SignatureThread(SymmetricEncryptManager manager, File plain, File folder, File idFile, Properties content, String cipherName, boolean sign) {
		this.manager = manager;
		this.plain = plain;
		this.folder = folder;
		this.idFile = idFile;
		this.content = content;
		this.cipherName = cipherName;
		this.sign = sign;
	}

	@Override
	public void run() {
		if (sign) {
			// 加密测试完成
			PBS pbs = PBS.instance(PBC.instance());
			try {
				byte[] plainHash = Hash.sha1(plain);
				IDIO io = new SimpleIDFileIOImpl(idFile);
				ID id = io.load();
				Signature signature = pbs.sign(id.getPersonalParameter(), id.getSignatureKey(), plainHash);
				content.putAll(signature.toProperties(SymmetricEncryptManager.SIGNATURE_PREFIX)); //$NON-NLS-1$
				content.putAll(id.getPersonalParameter().toProperties(SymmetricEncryptManager.PERSONAL_PARAMETER_PREFIX));
			} catch (IOException e) {
				manager.setError(true);
				manager.setComplete(true);
				return;
			}
			content.setProperty(SymmetricEncryptManager.SIGNED_MARK, "true"); //$NON-NLS-2$
		}
		File ibcKeyFile = new File(folder, cipherName); //$NON-NLS-1$
		try {
			OutputStream out = new FileOutputStream(ibcKeyFile);
			content.store(out, "do not edit this file"); //$NON-NLS-1$
			out.close();
		} catch (IOException e) {
			manager.setError(true);
		}
		manager.setComplete(true);
	}
}
